package com.sydx.controller;


import com.sydx.entity.Car;
import com.sydx.service.CarService;
import com.sydx.utils.MapControl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/car")
public class CarController {

    private static final String LIST = "car/list";
    private static final String ADD = "car/add";
    private static final String UPDATE = "car/update";

    @Autowired
    private CarService carService;

    @GetMapping("/add") // 跳转新增页面
    public String create(){
        return ADD;
    }

    @PostMapping("/create") // 写入数据
    @ResponseBody
    public Map<String,Object> create(@RequestBody Car car){
        int result = carService.create(car);
        if(result<=0){
            return MapControl.getInstance().error().getMap();
        }
        return MapControl.getInstance().success().getMap();
    }

    @PostMapping("/delete/{id}")
    @ResponseBody
    public Map<String,Object> delete(@PathVariable("id") Integer id){
        int result = carService.delete(id);
        if(result<=0){
            return MapControl.getInstance().error().getMap();
        }
        return MapControl.getInstance().success().getMap();
    }

    @PostMapping("/delete")
    @ResponseBody
    public Map<String,Object> delete(String ids){
        int result = carService.delete(ids);
        if(result<=0){
            return MapControl.getInstance().error().getMap();
        }
        return MapControl.getInstance().success().getMap();
    }

    @PostMapping("/update")
    @ResponseBody
    public Map<String,Object> update(@RequestBody Car car){
        int result = carService.update(car);
        if(result<=0){
            return MapControl.getInstance().error().getMap();
        }
        return MapControl.getInstance().success().getMap();
    }

    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Integer id, ModelMap modelMap){
        Car car = carService.detail(id);
        modelMap.addAttribute("car",car);
        return UPDATE;
    }

    @PostMapping("/query")
    @ResponseBody
    public Map<String,Object> query(@RequestBody Car car){
        List<Car> list = carService.query(car);
        // 分页
        Integer count = carService.count(car);
        return MapControl.getInstance().success().page(list,count).getMap();
    }

    @GetMapping("/list")
    public String list(){
        return LIST;
    }


}
